var config = require('../../config.js');
const app = getApp()
var getCaptcha = require('../common/js/getCaptcha.js');
var captcha = null
var phoneNum = null
var maxTime = 90
var currentTime = maxTime //倒计时的事件（单位：s）  
var interval = null

Page({
  data: {
    showButton: true,
    time: currentTime,
    mobileDisable: false
  },
  signUpSubmit: function (e) {
    var info = e.detail.value;
    // if (!info.name) {
    //   this.showInfo('请输入姓名')
    // } else 
    if (!info.mobile) {
      this.showInfo('请输入手机号');
    } else if (!info.password) {
      this.showInfo('请输入密码');
    } else if (!info.password2) {
      this.showInfo('请再次输入密码',"none");
    } else if (info.password != info.password2) {
      this.showInfo('两次密码不一样',"none");
    } else if (!info.captcha) {
      this.showInfo('请输入验证码');
    } 
    // else if (this.data.captcha == null || this.data.captcha == ''){
    //   this.showInfo('请获取验证码');
    // } 
    else if (this.data.captcha != info.captcha){
      this.showInfo('验证码不正确');
    }else{
      var regMobile = /^[1][3,4,5,6,7,8][0-9]{9}$/
      if (!regMobile.test(info.mobile)) {
        app.tip("手机号码格式不正确", "none");
        return false;
      }
      if (info.idNo != undefined && info.idNo != null && info.idNo != "") {
        var regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (!regIdNo.test(info.idNo)) {
          app.tip("身份证号填写有误", 'none')
          return false;
        }
      }
      //info.openid = app.openid
      this.signUp(info)
    }
  },
  showInfo: function (msg, icon) {
    if (msg) {
      wx.showToast({
        title: msg,
        icon: icon ? icon : 'loading',
        duration: 1000
      })
    }
  },
  input_phoneNum: function (e) {
    phoneNum = e.detail.value
  },
  getCaptcha: function () {
    if (phoneNum == null || phoneNum == '') {
      this.showInfo('请输入电话号码')
      return false
    }
    var regMobile = /^[1][3,4,5,6,7,8][0-9]{9}$/
    if (!regMobile.test(phoneNum)) {
      app.tip("手机号码格式不正确", "none");
      return false;
    }
    this.setData({
      able: true
    });
    getCaptcha.doRequest(this, phoneNum, 'reg')
  },
  captchaCallback: function (obj) {
    captcha = obj.message;
    this.data.captcha = captcha;
    console.info("发送验证码回调");
    console.info(captcha);
    this.setData({
      showButton: false
    })
    var that = this;
    currentTime = maxTime;
    interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime
      })
      if (currentTime <= 0) {
        that.setData({
          able: false
        });
        clearInterval(interval)
        currentTime = -1
      }
    }, 1000)
  },
  reSendPhoneNum: function () {
    if (phoneNum == null || phoneNum == '') {
      this.showInfo('请输入电话号')
      return false
    }
    var regMobile = /^[1][3,4,5,6,7,8][0-9]{9}$/
    if (!regMobile.test(phoneNum)) {
      app.tip("手机号码格式不正确", "none");
      return false;
    }
    this.setData({
      able: true
    });
    if (currentTime < 0) {
      var that = this
      currentTime = maxTime
      // interval = setInterval(function () {
      //   currentTime--
      //   that.setData({
      //     time: currentTime
      //   })
      //   if (currentTime <= 0) {
      //     that.setData({
      //       able: false
      //     });
      //     currentTime = -1
      //     clearInterval(interval)
      //   }
      // }, 1000)

      captcha = null
      
      // this.getCaptcha.doRequest(this, phoneNum)
      getCaptcha.doRequest(this, phoneNum, 'reg');

    } else {
      this.showInfo('短信已发到您的手机，请稍后重试')
    }
  },
  signUp: function (data) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: config.registerUrl,
      data: { "data": JSON.stringify(data) },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading()
        var result = res.data;
        console.log(res.data);
        if (result.code == 100) {
          that.showInfo('注册成功', 'success')
          app.loginMobile = data.mobile;
          wx.navigateTo({
            url: '/pages/login/login?mobile=' + data.mobile
          });
        } else {
          var errMsg;
          if (result && result.msg) {
            errMsg = result.msg
          } else {
            errMsg = res.statusCode + ":" + res.errMsg
          }
          that.showInfo(errMsg)
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log(res);
        var msg = '网络连接失败';
        if (res.errMsg) msg = res.errMsg;
        that.showInfo(msg)
      }
    })
  },
  changeProvince: function (e) {
    //e.detail.value中的值是数组的下标
    this.setData({
      provinceIndex: e.detail.value,
      province: this.data.provinceList[e.detail.value].administrativeDivisionName
    })
    getCityList(this.data.provinceList[e.detail.value].administrativeDivisionId, this);
  },
  changeCity: function (e) {
    //e.detail.value中的值是数组的下标
    this.setData({
      cityIndex: e.detail.value,
      city: this.data.cityList[e.detail.value].administrativeDivisionName,
      areaCode: this.data.cityList[e.detail.value].administrativeDivisionCode
    })
  },
  onLoad: function (options) {
    getProvinceList(this);
  },

})


//省选择器的数据加载
function getProvinceList(that) {
  wx.showLoading({
    title: '加载中'
  })
  wx.request({
    url: config.requestUrl + "administrativeDivision/getProvinceList",
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      wx.hideLoading()

      var data = res.data;
      if (data && data.code && data.code == 100) {
        var provinceLists = data.content;
        //console.log(provinceLists)
        //console.log(app.currentPosition);
        if (app.currentPosition == null) {
          that.setData({ provinceList: provinceLists, province: provinceLists[0].administrativeDivisionName })
          getCityList(provinceLists[0].administrativeDivisionId, that);
        } else {
          var provinceId = "";
          for (var i = 0; i < provinceLists.length; i++) {
            if (app.currentPosition.ad_info.province == provinceLists[i].administrativeDivisionName) {
              provinceId = provinceLists[i].administrativeDivisionId;
            }
          }
          that.setData({ provinceList: provinceLists, province: app.currentPosition.ad_info.province })
          getCityList(provinceId, that);
        }
      } else {
        var errMsg;
        if (data && data.msg) {
          errMsg = data.msg
        } else {
          errMsg = res.statusCode + ":" + res.errMsg
        }
        app.tip(errMsg, 'none')
      }
    },
    fail: function ({ errMsg }) {
      wx.hideLoading()
      app.tip(errMsg, 'none')
    }
  })
}

//市选择器的数据加载
function getCityList(provinceId, that) {
  console.info("市信息");
  wx.showLoading({
    title: '加载中'
  })
  wx.request({
    url: config.requestUrl + "administrativeDivision/getCityList",
    method: "POST",
    data: {
      "provinceId": provinceId
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      wx.hideLoading()

      var data = res.data;
      if (data && data.code && data.code == 100) {
        var cityLists = data.content;
        console.info("初始化市的值");
        if (app.currentPosition == null) {
          that.setData({ cityList: cityLists, city: cityLists[0].administrativeDivisionName, areaCode: cityLists[0].administrativeDivisionCode })
        } else {
          that.setData({ cityList: cityLists, city: app.currentPosition.ad_info.city, areaCode: app.currentPosition.ad_info.city_code.substr(3, app.currentPosition.ad_info.city_code.length) })
        }
      } else {
        var errMsg;
        if (data && data.msg) {
          errMsg = data.msg
        } else {
          errMsg = res.statusCode + ":" + res.errMsg
        }
        app.tip(errMsg, 'none')
      }
    },
    fail: function ({ errMsg }) {
      wx.hideLoading()
      app.tip(errMsg, 'none')
    }
  })
}